// ==UserScript==
// @name         TETA Study
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       icdcom(xnze.cn)
// @match        https://teta.ncet.edu.cn
// @match        https://teta.ncet.edu.cn/*
// @match        https://teta.ncet.edu.cn/nursery/study/index.do
// @match        https://teta.ncet.edu.cn/nursery/study/course/*
// @match        https://teta.ncet.edu.cn/nursery/study/home/showAssessResult.do
// @require      https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_openInTab
// @grant        GM_addOnLoadHook
// @grant        GM_addEventlistener

// ==/UserScript==

window.onload = function () {
  setTimeout(function () {
    let url = window.location.href;
    if (url.indexOf("course/index.do") !== -1) {
      console.log("检测到视频播放页");
      console.log(GM_getValue("studyTabs"));

      triggerFirstVideo();

      setTimeout(() => {
        playVideo();
      }, 2000);
    } else if (url.indexOf("showAssessResult.do") !== -1) {
      console.log("检测到考核详情表页");

      getCourseDataTolearn();
    } else if (url.indexOf("study/index.do") !== -1) {
      console.log("检测到课程列表页");
      const courseHoursToLearn = parseInt(prompt("请输入要学习的课时数"));

      openCourseDataTab();
      const courseToLearn = GM_getValue("courseData");
      //console.log(courseToLearn);

      // Get all the elements with class "main-10" which contain the course information
      const courseElements = document.querySelectorAll(".main-10");
      const courseList = getFullCourseList(courseElements);
      //console.log(courseList);

      const finalCourse = filterCourseDataToLearn(
        courseToLearn,
        courseList,
        courseHoursToLearn
      );

      doSomething(finalCourse);
      console.log(finalCourse);
    }
  }, 2000);
};

const sleep = (delay) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, delay);
  });
};

async function doSomething(finalCourse) {
  for (const e of finalCourse) {
    let studyTab = openStudyTab(
      e.vTrainCourseId,
      e.vTrainId,
      e.vCType,
      e.vStarted,
      e.vHomepageUrl
    );
    await sleep(5000);
  }
  GM_setValue("studyTabs", studyTabs);
}

function openCourseDataTab() {
  // Get the element with the onclick attribute
  const element = document.querySelector(".word10");

  // Extract the value from the onclick attribute
  const onclickAttributeValue = element.getAttribute("onclick");
  const match = onclickAttributeValue.match(/'([^']+)'/);

  if (match) {
    const extractedValue = match[1];
    GM_openInTab(
      "https://teta.ncet.edu.cn/nursery/study/home/showAssessResult.do?id=" +
        extractedValue,
      { active: true, insert: true, setParent: true }
    );
  } else {
    console.log("Value not found.");
  }
}

function getFullCourseList(courseElements) {
  // Define an array to store the extracted data
  const courseData = [];

  // Loop through each course element
  courseElements.forEach((courseElement) => {
    // Extract the course title
    const courseTitleElement = courseElement.querySelector(".info9 .text");
    const courseTitle = courseTitleElement
      ? courseTitleElement.textContent
      : "";

    // Extract the onclick attribute value
    const onclickAttributeValue = courseElement
      .querySelector(".word15")
      .getAttribute("onclick");

    // Extract parameters from the onclick attribute using a more flexible approach
    const params = onclickAttributeValue
      .match(/'([^']+)'/g)
      .map((param) => param.replace(/'/g, ""));

    if (params.length >= 5) {
      const [vTrainCourseId, vTrainId, vCType, vStarted, vHomepageUrl] = params;

      // Push the extracted data as an object into the courseData array
      courseData.push({
        courseTitle,
        vTrainCourseId,
        vTrainId,
        vCType,
        vStarted,
        vHomepageUrl,
      });
    }
  });

  return courseData;
}

function getCourseDataTolearn() {
  // Get the list of all course items
  const courseItems = document
    .querySelectorAll(".assessment-criteria-list")[1]
    .querySelectorAll("li");

  // Create an array to store the course data for incomplete courses
  const incompleteCourses = [];

  // Loop through each course item
  courseItems.forEach((courseItem, courseOrder) => {
    // Get the course name
    const courseNameElement = courseItem.querySelector(".w254 span");
    const courseName = courseNameElement ? courseNameElement.textContent : "";

    // Get the video duration (second <p> element)
    const videoDurationElement = courseItem.querySelector(
      "p:nth-child(2) span"
    );
    const videoDuration = videoDurationElement
      ? parseInt(videoDurationElement.textContent)
      : 0;

    // Get the course hours (the <p> element with class "w95")
    const courseHoursElement = courseItem.querySelector(".w95");
    const courseHours = courseHoursElement
      ? parseInt(courseHoursElement.textContent)
      : 0;

    // Get the completion status (the <p> element with class "class-hour")
    const completionStatusElement = courseItem.querySelector(".class-hour");
    const completionStatus = completionStatusElement
      ? completionStatusElement.textContent.trim()
      : "";

    // Check if the course is incomplete
    if (completionStatus === "未完成") {
      // Calculate the ratio of video duration to course hours
      const ratio = courseHours !== 0 ? videoDuration / courseHours : 0;

      // Push the course data into the incompleteCourses array
      incompleteCourses.push({
        courseName,
        courseOrder,
        videoDuration,
        courseHours,
        ratio,
      });
    }
  });

  // Sort the incomplete courses by the ratio in ascending order
  incompleteCourses.sort((a, b) => a.ratio - b.ratio);
  GM_setValue("courseData", incompleteCourses);
}

function filterCourseDataToLearn(courseToLearn, courseList, courseHoursRemain) {
  let courseHours = 0;
  let i = 0;

  const hashTable = new Map();

  for (const element of courseList) {
    hashTable.set(element.courseTitle, element);
  }

  const commonElements = [];

  while (
    ((courseHours += courseToLearn[i].courseHours),
    i < courseToLearn.length && courseHours < courseHoursRemain)
  ) {
    let course = hashTable.get(courseToLearn[i].courseName);
    course.videoDuration = courseToLearn[i].videoDuration;
    commonElements.push(course);
    i++;
  }

  return commonElements;
}

function triggerFirstVideo() {
  // Find the li element with the title "视频观看"
  const liElement = document.querySelector(
    'li.st_tree_content_title[title="视频观看"]'
  );

  // Initialize a variable to store the onclick attribute content
  let onclickContent = null;

  if (liElement) {
    // Find the next sibling ul element
    const ulElement = liElement.nextElementSibling;

    if (ulElement) {
      // Find the li with class "st_tree_play" under the ul
      const stTreePlayLi = ulElement.querySelector("li.st_tree_play");

      if (stTreePlayLi) {
        // Get the onclick attribute content
        const anchorElement = stTreePlayLi.querySelector("a");
        if (anchorElement) {
          onclickContent = anchorElement.getAttribute("onclick");
        }
      }
    }
  }

  // Log the onclick attribute content
  //console.log(onclickContent);

  // Use eval() to execute the code
  try {
    eval(onclickContent);
  } catch (error) {
    console.error("Error executing onclick content:", error);
  }
}

function playVideo() {
  // Get a reference to the iframe element by its id
  const iframe = document.getElementById("activityContent");

  // Check if the iframe element exists
  if (iframe) {
    // Access the content window of the iframe
    const iframeWindow = iframe.contentWindow;

    // Execute your code within the iframe's context immediately
    const player = iframeWindow.eduplayer.getPlayer("videoDiv");
    setTimeout(player.play(), 1000);
    player.pause();

    // Check if the player exists
    if (player) {
      let totalDurationInSeconds = player.K.duration;

      // Set the calculated duration in seconds to the form input elements
      const form = iframeWindow.document.getElementById("myForm");
      if (form) {
        form.querySelector("#realViewLength").value = totalDurationInSeconds;
        form.querySelector("#position").value = totalDurationInSeconds;
        form.querySelector("#maxPosition").value = totalDurationInSeconds;
      } else {
        console.log('Form with ID "myForm" not found within the iframe.');
      }
    }

    // Call your loopSubmit() and clearInterval() functions within the iframe
    iframeWindow.loopSubmit();
    iframeWindow.clearInterval(iframeWindow.vCheckorLooper);
  } else {
    console.log('The iframe element with id "activityContent" was not found.');
  }
}

function openStudyTab(
  vTrainCourseId,
  vTrainId,
  vCType,
  vStarted,
  vHomepageUrl
) {
  ajaxSubmit({
    url: "/nursery/study/index/checkStartCourse.do",
    params: {
      trainId: vTrainId,
      trainCourseId: vTrainCourseId,
    },
    onSuccess: function () {
      if (vHomepageUrl && httpPrefixRegex.test(vHomepageUrl)) {
        newPage = GM_openInTab(
          "https://teta.ncet.edu.cn/nursery/study/activity/urlcourse/gotoStudy.do?courseId=" +
            vTrainCourseId +
            "&trainId=" +
            vTrainId,
          { active: true, insert: true, setParent: true }
        );
      } else {
        if (vStarted == "true") {
          newPage = GM_openInTab(
            "https://teta.ncet.edu.cn/nursery/study/course/index.do?courseId=" +
              vTrainCourseId +
              "&trainId=" +
              vTrainId +
              "&courseType=" +
              vCType,
            { active: true, insert: true, setParent: true }
          );
        } else {
          layer.msg("该课程没有到达开始时间,您不能学习！", { icon: 2 });
        }
      }
    },
    onError: function (data) {
      layer.msg(data.responseText, { icon: 2 });
    },
  });
}
